<script setup>
import { ref, h, reactive, onBeforeMount } from 'vue'
import {
  NDataTable, NButton, NIcon, NModal, NCard, NForm, NSpace,
  NFormItem, NInput, NSwitch, useMessage, NRadioGroup, NRadio
} from 'naive-ui'
import { UserOutlined, LockOutlined } from '@vicons/antd'
import md5 from 'js-md5'
import http from '../http'

const columns = [
  { title: '用户', key: 'uid' },
  { title: '姓名', key: 'name' },
  { title: '角色', key: 'role' },
  {
    title: '状态',
    key: 'status',
    render(row, index) {
      return h(
        NSwitch, {
        value: row.status,
        onUpdateValue: (status) => {
          onSetUserStatus(row.uid, index, status)
        }
      })
    }
  },
  {
    title: '操作',
    key: 'action',
    render(row, index) {
      return h(NSpace, null, {
        default: () => [
          h(NButton, { type: 'info', onClick: () => onReset() }, { default: () => '重置' }),
          h(NButton, { type: 'error', onClick: () => onRemoveUser(row.uid, index) }, { default: () => '删除' })
        ]
      })
    }
  }
]

const data = ref([])

// 消息
const message = useMessage()


// 校验规则
const rules = {
  uid: { required: true, trigger: 'blur', message: '请输入用户' },
  name: { required: true, trigger: 'blur', message: '请输入姓名' },
  password: { required: true, trigger: 'blur', message: '请输入密码' },
  role: { required: true, trigger: ['blur', 'change'], message: '请选择角色' },
}

// 表单
const formRef = ref(null)

// 是否显示对话框
const showModal = ref(false)

// 关闭对话框
const onClose = () => {
  showModal.value = false
}

// 用户信息
const user = reactive({
  uid: '',
  name: '',
  password: '',
  role: '',
})

// 用户注册
const onAddUser = (e) => {
  e.preventDefault()
  formRef.value.validate(err => {
    if (!err) {
      user.password = md5(`${user.uid}-${user.password}`)
      http.post('/api/user/register', user).then(res => {
        if (res.data.status) {
          data.value.push({
            uid: user.uid,
            name: user.name,
            role: user.role,
            status: true,
          })
          showModal.value = false
          console.log('User.onAddUser => 用户注册成功')
          message.success('用户注册成功')
        } else {
          console.log(`User.onAddUser => 用户注册失败:${res.data.message}`)
          message.warning(res.data.message)
        }
      }).catch(err => {
        console.log(`User.onAdduser => 用户注册错误：${err.message}`)
        message.warning(err.message)
      })
    } else {
      // 字段校验失败
      for (let row of err) {
        console.log(`字段校验失败：${row[0].message}`)
      }
    }
  })
}

// 用户删除
function onRemoveUser(uid, index) {
  http.delete(`/api/user/remove/${uid}`).then(res => {
    if (res.data.status) {
      console.log(`User.onRemoveUser => 删除用户${uid}成功`)
      data.value.splice(index, 1)
      message.success(`删除用户${uid}成功`)
    } else {
      console.log(`User.onRemoveUser => 删除用户${uid}失败：${res.data.message}`)
      message.warning(`${res.data.message}`)
    }
  }).catch(err => {
    console.warn(`User.onRemoveUser => ${err}`)
    message.error(`${err}`)
  })
}

// 用户设置
function onSetUserStatus(uid, index, status) {
  http.post(`/api/user/set`, { uid: uid, status: status }).then(res => {
    if (res.data.status) {
      data.value[index].status = status
      console.log(`User.onSetUserStatus => 设置用户${uid}状态为${status}成功`)
    } else {
      console.warn(`User.onSetUserStatus => 设置用户${uid}状态${status}失败`)
      message.warning(`${res.data.message}`)
    }
  }).catch(err => {
    console.warn(`User.onSetUserStatus => 设置用户${uid}状态${status}错误`)
    message.error(`${err}`)
  })
}

// 预加载数据
onBeforeMount(() => {
  http.get('/api/user/list').then(res => {
    console.log(`User.onBeforeMount => 获取用户清单`)
    data.value = res.data
  }).catch(err => {
    console.warn(`User.onBeforeMount => 获取用户清单失败`)
  })
})
</script>

<template>
  <n-data-table :data="data" :columns="columns"></n-data-table>
  <div class="btn"><n-button type="primary" @click="showModal = true">新增用户</n-button></div>

  <n-modal v-model:show="showModal" :mask-closable="false">
    <n-card style="width: 380px" title="用户新增" :bordered="false" aria-modal="true" closable @close="onClose"
      :segmented="{ content: true }" :footer-style="{ 'text-align': 'center' }">

      <n-form :rules="rules" label-placement="left" :label-width="60" ref="formRef" :model="user">
        <n-form-item label="用户" path="uid">
          <n-input v-model:value="user.uid" placeholder="请输入用户">
            <template #prefix>
              <n-icon>
                <UserOutlined />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item label="姓名" path="name">
          <n-input v-model:value="user.name" placeholder="请输入姓名">
            <template #prefix>
              <n-icon>
                <UserOutlined />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item label="密码" path="password">
          <n-input v-model:value="user.password" placeholder="请输入密码" type="password">
            <template #prefix>
              <n-icon>
                <LockOutlined />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item label="角色" path="role">
          <n-radio-group v-model:value="user.role">
            <n-radio value="user">user</n-radio>
            <n-radio value="admin">admin</n-radio>
          </n-radio-group>
        </n-form-item>
      </n-form>

      <template #footer>
        <n-button type="primary" @click="onAddUser" block size="large">用户注册</n-button>
      </template>
    </n-card>
  </n-modal>
</template>


<style scoped>
.btn {
  text-align: center;
  margin-top: 10px;
}
</style>